<template>
  <div class="shopping container">
    <div class="shopping-wrap">
      <div class="shopping-header">
        <el-row type="flex" align="middle" justify="space-between" class="title">
          <div class="name">我的购物车({{ getGlobCartNumber }})</div>
        </el-row>
        <el-row type="flex" align="middle" class="navbar">
          <el-col :span="8" class="name">课程详情</el-col>
          <el-col :span="10" class="name">售价</el-col>
          <el-col :span="6" class="name">操作</el-col>
        </el-row>
      </div>
      <div class="shopping-list" v-if="paymentList.length">
        <div class="shopping-mhm" v-for="(list, listIndex) in paymentList" :key="listIndex">
          <el-row type="flex" align="middle" class="mhm-header">
            <el-checkbox v-model="list.checked" @change="handleselectAllChange(listIndex)">{{
              list.school_name
            }}</el-checkbox>
            <el-popover placement="bottom-start" trigger="hover">
              <div v-loading="loading" class="shopping-coupon-loading">
                <el-scrollbar class="shopping-coupon-scrollbar">
                  <div
                    class="shopping-coupon-popover"
                    v-for="(item, j) in list.coupon_list"
                    :key="j"
                  >
                    <template v-if="item.list.length > 0">
                      <template v-for="(ods, odsIndex) in item.list">
                        <template>
                          <el-row
                            type="flex"
                            align="middle"
                            class="item"
                            v-if="ods.user_use == 0"
                            :key="odsIndex"
                          >
                            <div class="card" :class="couponTypeClass[ods.coupon_type]">
                              <template v-if="ods.coupon_type == 1">
                                {{ ods.price | formatMoney }}
                              </template>
                              <template v-else-if="ods.coupon_type == 2">
                                {{ ods.discount | floatCount }}折
                              </template>
                              <template v-else-if="ods.coupon_type == 3">课程卡</template>
                            </div>
                            <div class="info">
                              <div class="name">
                                <template v-if="ods.coupon_type == 1">
                                  满{{ ods.maxprice | floatCount }}减{{ ods.price | floatCount }}
                                </template>
                                仅限
                                <span
                                  class="mhm"
                                  v-if="ods.coupon_type == 1 || ods.coupon_type == 2"
                                  >{{ ods.school_name }}</span
                                >
                                <span class="mhm" v-else-if="ods.coupon_type == 3">{{
                                  ods.course_title
                                }}</span>
                                使用
                              </div>
                              <div v-if="ods.use_etime" class="time">
                                {{ ods.use_stime | parseTime('{y}.{m}.{d}') }}-{{
                                  ods.use_etime | parseTime('{y}.{m}.{d}')
                                }}
                              </div>
                              <div v-else class="time">永久有效</div>
                            </div>
                            <el-button
                              class="receive"
                              :class="{
                                active: ods.user_has == 1
                              }"
                              plain
                              size="mini"
                              @click="handieReceiveCoupon(ods)"
                              :disabled="ods.user_has == 1"
                            >
                              {{ ods.user_has == 1 ? '已领取' : '领取' }}
                            </el-button>
                          </el-row>
                        </template>
                      </template>
                    </template>
                  </div>
                </el-scrollbar>
              </div>
              <div slot="reference" class="coupon-title" v-show="isSome(list.coupon_list)">
                领取优惠卷<i class="el-icon-arrow-down"></i>
              </div>
            </el-popover>
          </el-row>
          <div class="mhm-case">
            <el-row
              type="flex"
              class="item"
              v-for="(item, subIndex) in list.course_list"
              :key="subIndex"
            >
              <el-row type="flex" justify="center" class="checkbox">
                <el-checkbox
                  v-model="item.checked"
                  @change="handleChildCheckChange(listIndex)"
                ></el-checkbox>
              </el-row>
              <EduCourseImage
                :image="item.cover_url"
                :course-type="item.course_type"
                :border-radius="4"
                width="170px"
                height="94px"
                cursor="default"
              >
              </EduCourseImage>
              <el-row type="flex" justify="space-between" class="info">
                <el-row type="flex" align="middle">
                  <div class="name">{{ item.title }}</div>
                  <span class="card" v-if="item.has_course_card == 1">课程卡</span>
                </el-row>
                <el-row type="flex" class="dec">
                  <span>课时数：{{ item.section_count_count }}节</span>
                </el-row>
              </el-row>
              <el-row class="end" type="flex" justify="end">
                <div class="picrie">
                  <span v-if="isVip == 1">VIP价:</span>{{ item.user_price | formatMoney }}
                </div>
              </el-row>
              <el-row class="end" type="flex" justify="end">
                <el-link :underline="false" class="delete" @click="handieCourseDelebe(item)"
                  >删除</el-link
                >
              </el-row>
            </el-row>
          </div>
          <el-row type="flex" align="middle" justify="end" class="mhm-combined">
            <span class="name">合计：</span>
            <span class="money">{{ money(list) | formatMoney }}</span>
          </el-row>
        </div>
      </div>
      <edu-no-data
        v-else
        :size="250"
        text="还未加入课程哦~"
        margin-top="80px"
        margin-bottom="80px"
        :image="require('@/assets/images/public/shoppingcart_placeholder_img.png')"
      ></edu-no-data>

      <div ref="shopFooter" :style="{ 'padding-bottom': shopFixed ? '60px' : '0px' }"></div>
      <div v-if="paymentList.length > 0" class="shopping-footer" :class="{ isFixed: shopFixed }">
        <div class="shopping-column">
          <el-row type="flex" align="middle">
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <el-link :underline="false" class="delete" @click="handieCourseAllDelebe">删除</el-link>
          </el-row>
          <el-row type="flex" align="middle">
            <el-row type="flex" align="middle" class="combined">
              <span class="name">合计：</span>
              <span class="money">{{ handieMechanismTotal() | formatMoney }}</span>
            </el-row>
            <el-button type="primary" size="medium" @click="goOrder" :disabled="disabled"
              >去支付</el-button
            >
          </el-row>
        </div>
      </div>
    </div>

    <div class="course-wrap" v-if="courseList.length > 0">
      <div class="course-divider">
        <span class="line"></span>
        <img src="@/assets/images/public/shoppingcart_heart_icon.png" />
        <span class="text">精品推荐</span>
        <span class="line"></span>
      </div>
      <div class="course-list">
        <swiper :options="courseSwiperOption">
          <swiper-slide v-for="(item, index) in courseList" :key="index">
            <div class="item">
              <div class="picture">
                <EduCourseImage
                  :image="item.cover_url"
                  :course-type="item.course_type"
                  :border-radius="4"
                  height="100%"
                  @click="goCourse(item.id)"
                >
                  <!-- 直播时间 -->
                  <div v-if="item.course_type == 2 && item.start_time > 0" class="time">
                    {{ getFormateDate(item.start_time) }}
                  </div>
                </EduCourseImage>
              </div>
              <div class="content">
                <div class="title" @click="goCourse(item.id)">{{ item.title }}</div>
                <div class="parallel">
                  <div class="num">{{ item.sale_count }}人在学</div>
                  <div class="price" v-if="item.user_price > 0">
                    {{ item.user_price | formatMoney }}
                  </div>
                  <div v-else class="free">免费</div>
                </div>
              </div>
            </div>
          </swiper-slide>
        </swiper>
        <div class="swiper-button-prev swiper-button-white"></div>
        <div class="swiper-button-next swiper-button-white"></div>
      </div>
    </div>
  </div>
</template>

<script>
import EduCourseImage from '@/components/EduCourseImage'
import EduNoData from '@/components/EduNoData'
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import { parseTime } from '@/utils/filters.js'
import 'swiper/css/swiper.css'
import { mapState } from 'vuex'
export default {
  components: {
    EduNoData,
    EduCourseImage,
    Swiper,
    SwiperSlide
  },
  data() {
    return {
      parseTime,
      couponList: [],
      paymentList: [],
      checkAll: false, // 所有机构选中的状态
      paymentCourseList: '', // 控制机构选中
      loading: false,
      disabled: false,
      courseTypeClass: {
        1: 'video',
        2: 'live',
        3: 'multipart',
        4: 'classes'
      },
      couponTypeClass: { 1: 'youhui', 2: 'dazhe', 3: 'kechengka' },
      shopFixed: false,
      footerTop: 0,
      courseList: [],
      courseSwiperOption: {
        slidesPerView: 4,
        spaceBetween: 20,
        loop: false,
        loopAdditionalSlides: 0,
        navigation: {
          nextEl: `.course-list .swiper-button-next`,
          prevEl: `.course-list .swiper-button-prev`
        }
      }
    }
  },
  inject: ['reload'],
  created() {
    this.paymentInitData()
    this.getCourseSplendid()
  },
  computed: {
    // 购物车数量
    ...mapState({
      getGlobCartNumber: state => state.projectSetting.globCartNumber
    }),
    // 用户会员状态
    isVip() {
      return this.$store.getters['user/accountInfo'].is_vip
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 购物车数据初始化
    paymentInitData() {
      this.$api.getCart(res => {
        // 初始完成添加 checked 属性
        res.data.forEach(item => {
          this.$set(item, 'checked', false)
          item.course_list.forEach(subItem => {
            this.$set(subItem, 'checked', false)
          })
          // 获取机构的优惠卷
          this.$api.getCouponSchool(
            {
              mhm_id: item.mhm_id,
              group: 0
            },
            res => {
              this.$set(item, 'coupon_list', res.data)
            }
          )
        })
        this.paymentList = res.data
        this.$nextTick(() => {
          this.footerTop = this.$refs.shopFooter.getBoundingClientRect().bottom
          this.handleScroll()
        })
      })
    },
    // 推荐课程
    getCourseSplendid() {
      this.$api.getCourseList(
        {
          order: 'splendid',
          page: 1,
          count: 10
        },
        res => {
          const { data } = res
          this.courseList = data.data
        }
      )
    },
    // 领取卡卷
    handieReceiveCoupon(item) {
      this.$api.createCouponDerive(
        item.id,
        {},
        res => {
          this.$message.success(res.msg)
          item.user_has = 1
        },
        error => {
          this.$message.error(error.msg)
        }
      )
    },
    // 机构全选
    handleCheckAllChange() {
      this.paymentList.forEach(item => {
        item.checked = this.checkAll
        item.course_list.forEach(subItem => {
          subItem.checked = this.checkAll
        })
      })
    },
    // 产品全部选中改变全选
    handleCheckAll() {
      var that = this
      var first = that.paymentList.filter(item => {
        return item.checked == true
      })
      first.length == that.paymentList.length ? (that.checkAll = true) : (that.checkAll = false)
    },
    // 产品全选
    handleselectAllChange(i) {
      this.paymentList[i].course_list.forEach(subItem => {
        subItem.checked = this.paymentList[i].checked
      })
      this.handleCheckAll()
    },
    // 产品选中
    handleChildCheckChange(i) {
      var firstItem = this.paymentList[i].course_list.every(citem => citem.checked)
      firstItem ? (this.paymentList[i].checked = true) : (this.paymentList[i].checked = false)
      this.handleCheckAll()
    },
    // 处理商品总价
    handieMechanismTotal() {
      var that = this
      let allprice = 0 // 总价
      that.paymentList.forEach(item => {
        item.course_list.forEach(subItem => {
          if (subItem.checked == true) {
            allprice += parseFloat(subItem.user_price, 2)
          }
        })
      })
      return allprice.toFixed(2)
    },
    // 计算机构总价
    money(item) {
      let money = 0
      item.course_list.forEach(item2 => {
        if (item2.checked == true) {
          money += parseFloat(item2.user_price, 2) // 商品价格转换成浮点数累加,保留两位小数
        }
      })
      return money.toFixed(2)
    },
    // 删除课程
    handieCourseDelebe(item) {
      if (item.checked) {
        this.$api.deleteCart({ course_ids: item.id.toString() }, res => {
          this.$message.success(res.msg, res => {
            this.reload()
          })
          this.$store.dispatch('projectSetting/setGlobCartNumber')
        })
      } else {
        this.$message.error('请选择要删除的商品')
      }
    },
    // 返回选中课程的id
    handleCourseId() {
      var that = this
      let arr = []
      // 获取要删除课程的id
      that.paymentList.forEach((item, i) => {
        item.course_list.forEach((subItem, j) => {
          if (subItem.checked == true) {
            arr.push(subItem.id)
          }
          that.paymentCourseList = arr.join(',')
        })
      })
    },
    // 删除课程多选
    handieCourseAllDelebe() {
      var that = this
      that.handleCourseId()
      if (that.paymentCourseList != '') {
        this.$api.deleteCart({ course_ids: that.paymentCourseList }, res => {
          this.$message.success(res.msg, res => {
            this.reload()
          })
          this.$store.dispatch('projectSetting/setGlobCartNumber')
        })
      } else {
        this.$message.error('请选择删除课程')
      }
    },
    // 提交订单
    goOrder() {
      var that = this
      that.handleCourseId()
      that.disabled = true // 禁止重复点击
      if (that.paymentCourseList == '') {
        this.$message.error('请选择课程', () => {
          that.disabled = false
        })
        return
      }

      // 提交的订单是否有课程卡
      let tmep = that.paymentList.some(it =>
        it.course_list.some(item => item.checked && item.has_course_card == 1)
      )
      if (tmep) {
        this.$messageBox
          .confirm('订单含有课程卡课程，是否取消勾选？', {
            confirmButtonText: '继续支付',
            cancelButtonText: '去取消'
          })
          .then(() => {
            this.$router.push({
              path: '/buy/checkout',
              query: {
                course_ids: that.paymentCourseList
              }
            })
          })
          .catch(() => {
            that.disabled = false
          })
      } else {
        this.$router.push({
          path: '/buy/checkout',
          query: {
            course_ids: that.paymentCourseList
          }
        })
      }
    },
    isSome(arr) {
      if (!arr) return false
      return arr.some(item => item.list.length > 0)
    },
    handleScroll() {
      const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      this.shopFixed = this.footerTop > windowHeight + scrollTop - 60
    },
    // 跳转课程
    goCourse(id) {
      this.$router.push({
        path: '/course/' + id
      })
    },
    getFormateDate(timestamp) {
      const format = '{y}-{m}-{d}'
      const now = new Date() // 当前
      if (timestamp.toString().length == 10) timestamp *= 1000
      const date = new Date(timestamp)
      const nextDate = function(date, amount = 1) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount)
      }
      // 当前年
      if (now.getFullYear() == date.getFullYear()) {
        if (parseTime(now, format) == parseTime(date, format)) {
          return parseTime(timestamp, '今天 {h}:{i}')
        } else if (parseTime(nextDate(now), format) == parseTime(date, format)) {
          return parseTime(timestamp, '明天 {h}:{i}')
        } else {
          return parseTime(timestamp, '{m}月{d}日 {h}:{i}')
        }
      } else {
        return parseTime(timestamp, '{y}年{m}月{d}日 {h}:{i}')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
// 卡卷
.shopping-coupon-loading {
  width: 350px;
}
.shopping-coupon-scrollbar {
  height: 330px;
  ::v-deep .el-scrollbar__wrap {
    overflow-x: auto;
  }
}
.shopping-coupon-popover {
  .item {
    padding: 4px 0;
  }
  .card {
    width: 60px;
    height: 32px;
    font-size: 16px;
    font-weight: 700;
    color: #fff;
    line-height: 32px;
    text-align: center;
    background-size: 100% 100%;
    &.youhui {
      background-image: url('../../assets/images/public/manjian.png');
    }
    &.dazhe {
      background-image: url('../../assets/images/public/dazhe.png');
    }
    &.kechengka {
      background-image: url('../../assets/images/public/lesson.png');
    }
  }
  .info {
    flex: 1;
    margin-right: 10px;
    margin-left: 10px;
    .name {
      color: $text-color-secondary;
      font-size: 13px;
      .mhm {
        @include edu-color-auxiliary;
      }
    }
    .time {
      font-size: 12px;
      color: $text-color-auxiliary;
    }
  }
  .receive {
    border-radius: 0;
    padding: 7px 0;
    width: 60px;
    &.active {
      border-color: #fff;
    }
  }
}

.shopping {
  margin-top: 10px;
  .shopping-wrap {
    background-color: #fff;
  }
  .shopping-header {
    .title {
      padding: 0 30px;
      height: 44px;
      .name {
        font-size: 16px;
        color: $text-color-import;
      }
    }
    .navbar {
      padding: 0 65px;
      height: 44px;
      background-color: #f5f5f5;
      .name {
        text-align: right;
        font-size: 14px;
        color: $text-color-secondary;
        &:nth-child(1) {
          text-align: center;
        }
      }
    }
  }
  .shopping-list {
    margin-top: 24px;
    padding: 0 30px;
    .shopping-mhm {
      margin-bottom: 20px;
      .mhm-header {
        height: 44px;
        .coupon-title {
          margin-left: 20px;
          padding: 2px 5px;
          cursor: pointer;
          font-size: 12px;
          color: $text-color-price;
          border: 1px dashed $text-color-price;
        }
      }
      .mhm-case {
        border: 1px solid #dcdfe6;
        padding: 0 20px;
        .item + .item {
          border-top: 1px solid #dcdfe6;
        }
        .item {
          padding: 20px 15px 20px 0;
        }
        .checkbox {
          width: 30px;
          flex-direction: column;
        }
        .info {
          width: 385px;
          margin-left: 20px;
          padding-bottom: 15px;
          flex-direction: column;
          .name {
            max-width: 330px;
            font-size: 13px;
            color: $text-color-import;
            line-height: 18px;
            @include ellipsisLine(2);
            padding: 1px 0;
          }
          .card {
            margin-left: 7px;
            color: $text-color-free;
            border: 1px solid $text-color-free;
            font-size: 12px;
            padding: 3px 5px;
            border-radius: 2px;
          }
          .dec {
            font-size: 12px;
            color: $text-color-secondary;
            span + span {
              margin-left: 20px;
            }
          }
        }
        .end {
          flex: 1;
          align-self: flex-start;
        }
        .picrie {
          color: $text-color-price;
          font-size: 14px;
        }
        .delete {
          font-size: 14px;
          color: $text-color-secondary;
        }
      }
      .mhm-combined {
        height: 64px;
        padding: 0 20px;
        border: 1px solid #dcdfe6;
        border-top: 0;
        font-size: 14px;
        .name {
          color: $text-color-import;
        }
        .money {
          color: $text-color-price;
        }
      }
    }
  }
  .shopping-footer {
    position: static;
    transform: none;
    &.isFixed {
      position: fixed;
      transform: translateZ(0px);
      top: auto;
      left: 0;
      right: 0;
      bottom: 0px;
      z-index: 99;
      background: #ffffff;
      box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.06);
      .shopping-column {
        border-top: none;
      }
    }
  }
  .shopping-column {
    background-color: #ffffff;
    padding: 0 30px;
    height: 60px;
    width: 1200px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid #dcdfe6;
    box-sizing: border-box;
    margin: 0 auto;
    &.isFixed {
      position: fixed;
      transform: translateZ(0px);
      top: auto;
      bottom: 0px;
      z-index: 99;
    }
    .delete {
      margin-left: 30px;
      font-size: 14px;
      color: $text-color-secondary;
    }
    .combined {
      width: 180px;
      .name {
        font-size: 13px;
        color: $text-color-secondary;
      }
      .money {
        font-size: 18px;
        color: $text-color-price;
      }
    }
  }

  .course-wrap {
    margin-top: 20px;
    padding: 40px 0;
    background-color: #ffffff;
    .course-divider {
      display: flex;
      align-items: center;
      justify-content: center;
      .line {
        margin: 0 20px;
        width: 100px;
        height: 1px;
        background-color: #dcdfe6;
      }
      .text {
        margin-left: 7px;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
    .course-list {
      margin-top: 40px;
      position: relative;
      padding: 0 40px;
      .swiper-button-prev,
      .swiper-button-next {
        outline: none;
        width: 20px;
        height: 20px;
        top: 72.5px;
        margin-top: -10px;
        border-radius: 50%;
        color: #b7bac1;
        &:after {
          font-size: 16px;
        }
        &:hover {
          @include edu-color-primary;
        }
      }
      .swiper-button-prev.swiper-button-disabled,
      .swiper-button-next.swiper-button-disabled {
        pointer-events: auto;
        &:hover {
          color: #b7bac1 !important;
        }
      }
      .swiper-button-prev {
        left: 10px;
      }
      .swiper-button-next {
        right: 10px;
      }
      .item {
        .picture {
          height: 145px;
          position: relative;
          .time {
            padding: 0 5px;
            height: 20px;
            font-size: 12px;
            color: #ffffff;
            line-height: 20px;
            background: rgba(48, 49, 51, 0.59);
            border-radius: 3px;
            position: absolute;
            bottom: 6px;
            left: 7px;
          }
        }
        .content {
          margin-top: 15px;
          .title {
            font-size: 16px;
            font-weight: 500;
            color: $text-color-import;
            @include ellipsis;
            cursor: pointer;
          }
          .parallel {
            display: flex;
            align-items: center;
            margin-top: 15px;
            .num {
              flex: 1;
              min-width: 0;
              font-size: 14px;
              font-weight: 400;
              color: $text-color-auxiliary;
            }
            .price,
            .free {
              font-size: 18px;
              font-weight: 500;
              margin-left: 5px;
            }
            .price {
              color: $text-color-price;
            }
            .free {
              color: $text-color-free;
            }
          }
        }
      }
    }
  }
}
</style>
